import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Space, Button, Table, Tag, Input, Select, Form } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import { useHistory } from 'react-router-dom';
import SoundTempPop from './components/SoundTempPop';
import { SeatSoundTempResponse } from 'seats/schema/SoundManage';
import { getSeatSoundTempList } from 'seats/servers/servers';
import { clearNull } from 'utils/tools';
import './style.scss';
/**
 * 录音模板列表
 */
const SeatSoundTempList: React.FC = () => {
  const history = useHistory();
  const childRef = useRef();
  const searchRef = useRef<any>({
    searchText: '',
    searchState: '',
  });

  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  // 数据总数
  const [total, setTotal] = useState<number>(0);
  // 查询条件condition
  const [searchText, setSearchText] = useState<string>('');
  const [searchState, setSearchState] = useState<0 | 1 | ''>('');

  // table列表数据
  const [tableData, setTableData] = useState<SeatSoundTempResponse[]>([]);
  // 模板状态选项
  const statusOption = [
    {
      value: '',
      label: '全部',
    },
    {
      value: 1,
      label: '已完成',
    },
    {
      value: 0,
      label: '待录音',
    },
  ];
  /**
   * 查询table数据
   */
  const initData = useCallback(async () => {
    setTableLoading(true);
    try {
      const res = await getSeatSoundTempList(
        clearNull({
          pageNo: current,
          pageSize: pageSize,
          condition: searchRef.current.searchText,
          templateStatus: searchRef.current.searchState,
          type: 0,
        })
      );
      const { data, count } = res;
      setTableData(data || []);
      setTotal(Number(count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [current, pageSize]);

  useEffect(() => {
    initData();
  }, [initData]);

  /**
   * 新增
   */
  const handleAdd = () => {
    (childRef.current as any).open({}, () => {
      // 回调函数：操作成功，刷新列表
      refreshTable(1);
    });
  };
  /**
   * 编辑
   */
  const handleEdit = (obj: SeatSoundTempResponse) => {
    (childRef.current as any).open(obj, () => {
      // 回调函数：操作成功，刷新列表
      refreshTable();
    });
  };
  /**
   * 设置搜索条件
   */
  const handleSearch = () => {
    searchRef.current = {
      searchText: searchText,
      searchState: searchState,
    };
  };

  /**
   * 重置搜索条件
   */
  const resetSearch = () => {
    setSearchText('');
    setSearchState('');
    searchRef.current = {
      searchText: '',
      searchState: '',
    };
  };

  /**
   * 对table数据进行刷新：新增，编辑
   * @param pageNum 刷新页码
   */
  const refreshTable = async (pageNum?: number) => {
    if (pageNum) {
      current === pageNum ? initData() : setCurrent(pageNum);
    } else {
      initData();
    }
  };

  /**
   * Table列描述数据对象
   */
  const columns: ColumnsType<SeatSoundTempResponse> = [
    {
      title: '序号',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
      width: 70,
    },
    {
      title: '录音模板名称',
      dataIndex: 'templateName',
    },
    {
      title: '机器人名称',
      dataIndex: 'robotName',
    },
    {
      title: '机器人版本',
      dataIndex: 'robotVersionName',
      render: (text, record, index) => {
        return (
          <>
            {text}
            <span style={{ marginLeft: '10px' }}>
              {record.robotVersionStatus === 'online' && <Tag color="green">已上线</Tag>}
              {record.robotVersionStatus === 'offline' && <Tag color="volcano">已下线</Tag>}
              {record.robotVersionStatus === 'draft' && <Tag color="blue">草稿</Tag>}
            </span>
          </>
        );
      },
    },
    {
      title: 'TTS',
      dataIndex: 'ttsName',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'templateStatus',
      width: 100,
      render: (text, record, index) => {
        return text ? '已完成' : '待录音';
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 200,
      render: (text, record, index) => (
        <Space size="small">
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button
            type="link"
            onClick={() => {
              history.replace(
                `/webseats/seats/soundManage/soundLibrary?templateId=${record.templateId}`
              );
            }}
          >
            录音库
          </Button>
        </Space>
      ),
    },
  ];
  return (
    <>
      <div className="mgr-header">
        <div className="mgr-header-left">
          <Form layout="inline">
            <Form.Item>
              <Input
                placeholder="请输入录音模板名称或者机器人名称"
                style={{ width: 300 }}
                value={searchText}
                onChange={e => {
                  console.log('输入的查询条件', e.target.value.trim());
                  setSearchText(e.target.value.trim());
                }}
              />
            </Form.Item>
            <Form.Item label="状态">
              <Select
                style={{ width: 120 }}
                value={searchState}
                options={statusOption}
                onChange={(val: 0 | 1 | '') => {
                  console.log('选择的录音模板状态', val);
                  setSearchState(val);
                }}
              />
            </Form.Item>
            <Form.Item>
              <Space size="middle">
                <Button
                  type="primary"
                  onClick={() => {
                    handleSearch();
                    refreshTable(1);
                  }}
                >
                  搜索
                </Button>
                <Button
                  type="primary"
                  ghost
                  onClick={() => {
                    resetSearch();
                    refreshTable(1);
                  }}
                >
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
        <div className="mgr-header-right">
          <Button type="primary" onClick={() => handleAdd()}>
            新建录音模板
          </Button>
        </div>
      </div>
      <div className="mgr-table">
        <Table
          scroll={{ x: '100%' }}
          loading={tableLoading}
          columns={columns}
          dataSource={tableData}
          rowKey="templateId"
          pagination={{
            current: current,
            total: total,
            pageSize: pageSize,
            showSizeChanger: true,
            // 改条数/页
            onShowSizeChange: (current, size) => {
              setPageSize(size);
            },
            // 改页码
            onChange: current => {
              setCurrent(current);
            },
            showTotal: total => `共${total}条`,
          }}
        />
      </div>
      <SoundTempPop cRef={childRef}></SoundTempPop>
    </>
  );
};

export default SeatSoundTempList;
